import React, {useContext, useEffect, useRef, useState} from "react";
import {Button, Form, Input, Modal, Table} from "antd";
import {DeleteOutlined, ExclamationCircleOutlined} from "@ant-design/icons";
import axios from "axios";

const { confirm } = Modal;

const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            {/*生产者*/}
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

const EditableCell = ({ title, editable, children, dataIndex, record, handleSave, ...restProps }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
        if (editing) inputRef.current.focus();
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({
            [dataIndex]: record[dataIndex],
        });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();
            toggleEdit();
            handleSave({ ...record, ...values });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };

    let childNode = children;

    if (editable) {
        childNode = editing ? (
            <Form.Item style={{margin: 0}} name={dataIndex} rules={[{required: true, message: `${title}不能为空`,},]}>
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
            <div className="editable-cell-value-wrap" style={{paddingRight: 24}} onClick={toggleEdit}>
                {children}
            </div>
        );
    }

    return <td {...restProps}>{childNode}</td>;
};



export default function NewsCategory() {
    const [dataSource, setDataSource] = useState([]);
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const addFormRef= useRef(null);

    useEffect(()=>{
        axios.get('/api/categories').then(response=>{
            setDataSource(response.data);
        });
    }, []);

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render: (id)=><b>{id}</b>
        },
        {
            title: '栏目名称',
            dataIndex: 'title',
            onCell: (record) => ({
                record,
                editable: true,
                dataIndex: 'title',
                title: '栏目名称',
                handleSave,
            }),
        },
        {
            title: '操作',
            key: 'operation',
            render: (record) => {
                return (
                    <Button danger shape="circle" icon={<DeleteOutlined />} onClick={()=>handleDelete(record)}/>
                )
            },
        },
    ];

    // 修改分类
    const handleSave = (record) => {
        /*
        setDataSource(dataSource.map(item=>{
            if(item.id===record.id) {
                return { id: item.id, title: record.title, value: record.title}
            }
            return item;
        }));
        */

        const newData = [...dataSource];
        const index = newData.findIndex((item) => record.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, { id: item.id, title: record.title, value: record.title });
        setDataSource(newData);

        axios.put(`/api/categories/${record.id}`, { title: record.title, value: record.title });
    };

    // 删除分类
    const handleDelete= (record)=>{
        confirm({
            title: '是否想要删除此项?',
            icon: <ExclamationCircleOutlined />,
            content: '删除操作不可撤回，请谨慎操作!!!',
            onOk() {
                setDataSource(dataSource.filter(data=>{
                    return data.id !== record.id;
                }));
                axios.delete(`/api/categories/${record.id}`);
            },
            onCancel() {
                // console.log('Cancel');
            },
        });
    }

    // 添加分类
    const handleAddFormOk= ()=>{
        addFormRef.current.validateFields().then(values=>{
            setIsAddModalVisible(false);
            axios.post('/api/categories', {
                title: values.title,
                value: values.title
            }).then(response=>{
                setDataSource([...dataSource, {
                    ...response.data
                }]);
                addFormRef.current.resetFields();
            });
        })
    }
    const handleAddFormCancel= ()=>{
        setIsAddModalVisible(false);
        addFormRef.current.resetFields();
    }

    return (
        <div>
            <div style={{margin: '20px 0'}}>
                <Button type="primary" onClick={ ()=>setIsAddModalVisible(true)}>添加分类</Button>
            </div>

            <Table dataSource={dataSource} columns={columns}
                   pagination={{ pageSize: 5 }} rowKey={ item=>item.id }
                   components={{
                       body: {
                           row: EditableRow,
                           cell: EditableCell,
                       }
                   }}
            />

            <Modal title="添加分类" visible={isAddModalVisible} okText="添加" cancelText="取消"
                   onOk={handleAddFormOk} onCancel={handleAddFormCancel}>
                <Form autoComplete="off" layout="vertical" ref={ addFormRef }>
                    <Form.Item label="栏目名称" name="title" rules={[{ required: true, message: '请输入栏目名称!' }]}>
                        <Input />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
}
